package com.zhang.controller;

import cn.hutool.core.map.MapUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhang.common.DTO.LoginDto;
import com.zhang.common.lang.Const;
import com.zhang.common.lang.Result;
import com.zhang.entity.User;
import com.zhang.service.UserService;
import com.zhang.utils.JwtUtil;
import com.zhang.utils.ShiroUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;


import javax.servlet.http.HttpServletResponse;

//登陆接口
@RestController
public class AuthController {

    @Autowired
    UserService userService;
    @Autowired
    JwtUtil jwtUtil;

    @PostMapping("/login")
    public Result login(@RequestBody @Validated LoginDto loginDto, HttpServletResponse response) {

        User user = userService.getOne(new QueryWrapper<User>().eq("username", loginDto.getUsername()));

        Assert.notNull(user, "用户不存在");   //user为空会抛 IllegalArgumentException 异常
        if (!user.getPassword().equals(SecureUtil.md5(loginDto.getPassword()))) { //密码不正确
            return Result.fail("密码不正确");
        }

        String jwt = jwtUtil.generateToken(user.getId());   //创建jwt
        response.setHeader(jwtUtil.getHeader(),jwt);
        response.setHeader("Access-Control-Expose-Headers",jwtUtil.getHeader());    //使前端能够访问到此响应头

        return Result.success(MapUtil.builder()     //返回一些用户信息
                            .put("id",user.getId())
                            .put("username",user.getUsername())
                            .put("avatar",user.getAvatar())
                            .put("nickname",user.getNickname())
                            .put("email",user.getEmail()).map());
    }

    //用于token自动登录
    @PostMapping("/loginbytoken")
    public Result loginByToken(){
        return Result.success(ShiroUtil.getProfile());
    }

    @RequiresAuthentication
    @PostMapping("/logout")
    public Result logout(){
        SecurityUtils.getSubject().logout();
        return Result.success("");
    }
}
